package com.hotkid.ceo.jetpack.myjetpackmvvm.base

import android.app.Dialog
import android.content.Context
import android.content.DialogInterface
import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.InputMethodManager
import android.widget.FrameLayout
import androidx.viewbinding.ViewBinding
import com.google.android.material.bottomsheet.BottomSheetBehavior
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
import com.hotkid.ceo.jetpack.myjetpackmvvm.R
import com.yechaoa.yutilskt.DisplayUtil

abstract class BaseBottomSheetDialog<VB:ViewBinding>:BottomSheetDialogFragment() {
    protected open lateinit var mBinding:VB
    private var isFull=true

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setStyle(STYLE_NORMAL, R.style.BottomSheetDialog)
    }

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        val dialog=super.onCreateDialog(savedInstanceState)
        mBinding=getViewBinding()
        dialog.setContentView(mBinding.root)
        isNeedFull()
        initView(mBinding.root)
        return dialog
    }

    /**
     * 初始化view的相关的控件
     */
    abstract fun initView(root: View)

    /**
     * 是否需要全屏显示，默认显示全屏
     */
    private fun isNeedFull(isNeed:Boolean=true) {
        isFull=isNeed
    }

    abstract fun getViewBinding(): VB

    override fun onStart() {
        super.onStart()
        if (isFull){
            val view=dialog?.window?.findViewById<FrameLayout>(com.google.android.material.R.id.design_bottom_sheet)
            view!!.layoutParams.height=ViewGroup.LayoutParams.MATCH_PARENT
            val behavior=BottomSheetBehavior.from(view)
            //设置弹出的高度
            behavior.peekHeight=DisplayUtil.getScreenHeight()
            //设置展开的状态
            behavior.state=BottomSheetBehavior.STATE_EXPANDED
        }
    }

    override fun onCancel(dialog: DialogInterface) {
        hideKeyBoard()
        super.onCancel(dialog)
    }

    override fun dismiss() {
        hideKeyBoard()
        super.dismiss()
    }

    private fun hideKeyBoard() {
        val imm=context?.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        val view=dialog?.window?.currentFocus
        view?.let {
            imm.hideSoftInputFromWindow(view.windowToken,InputMethodManager.HIDE_NOT_ALWAYS)
        }
    }
}